package com.lrz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lrz.common.IdWorker;
import com.lrz.common.Result;
import com.lrz.common.StatusCode;
import com.lrz.dao.ArticleMapper;
import com.lrz.dao.UserMapper;
import com.lrz.pojo.Article;
import com.lrz.pojo.User;
import com.lrz.pojo.dto.UserDTO;
import com.lrz.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IdWorker idWorker;

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public Result register(User user) {
        User user1 = new User();
        user1.setId(idWorker.nextId());
        user1.setUsername(user.getUsername());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User user2 = userMapper.selectOne(wrapper);
//        System.out.println(user2);
        if (user2 != null){
            return new Result(false, StatusCode.ERROR, "用户名重复");
        }else {
            userMapper.insert(user);
            return new Result(true, StatusCode.OK, "注册成功", user);
        }
    }

    @Override
    public Result login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user1 = userMapper.selectOne(wrapper);
        if (user1 != null && user1.getPassword().equals(password)){
            return new Result(true, StatusCode.OK, "登录成功", user1);
        }else {
            return new Result(false, StatusCode.ERROR, "用户名或密码错误");
        }
    }

    @Override
    public Result update(User user) {
        int i = userMapper.updateById(user);
        if (i == 1)
            return new Result(true, StatusCode.OK, "修改成功");
        else
            return new Result(false,StatusCode.ERROR,"修改失败");
    }

    @Override
    public Result userInformation(Long userId) {
        UserDTO userDTO = new UserDTO();
        userDTO.setUser(userMapper.selectById(userId));
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        userDTO.setArticleList(articleMapper.selectList(wrapper));
        return new Result(true,StatusCode.OK,"查询成功", userDTO);
    }
}
